package com.cha.chaApp.family.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cha.chaApp.family.dao.FamilyDao;
import com.cha.chaApp.family.service.FamilyService;
import com.cha.chaApp.family.vo.FamilyVo;
import com.cha.chaApp.sys.user.dao.UserDao;
import com.cha.chaCommon.core.entity.Family;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class FamilyServiceImpl
        extends ServiceImpl<FamilyDao, Family>
        implements FamilyService {

    @Autowired
    private FamilyDao familyDao;

    @Autowired
    private UserDao userDao;

    @Override
    public FamilyVo getFamilyInfoByUserId(Long userId) {
        // 使用mybatisplus根据userId查询家庭id,在根据家庭id查询家庭信息
        Family family = familyDao.selectOne(new QueryWrapper<Family>().eq("user_id", userId));
        System.out.println("FamilyUserId: " + family.getUserId());

        // 把family的数据转换为FamilyVo
        FamilyVo familyVo = new FamilyVo(family);
        System.out.println("第一次的familyVo: " + familyVo);

        // 使用该家庭的userId来获取家庭成员信息
        if (family != null) {
            String userIdStr = family.getUserId();
            String[] userIdArr = userIdStr.split(",");
            System.out.println("userIdArr: " + Arrays.toString(userIdArr));

            // 创建一个空List来存储家庭成员名称
            List<String> usernameList = new ArrayList<String>();
            // 遍历userIdArr，获取每个用户的姓名,并添加到usernameList中,再将usernameList赋值给familyVo
            for (String id : userIdArr) {
                String username = userDao.selectById(id).getName();
                System.out.println("username: " + username);
                usernameList.add(username);
                familyVo.setUserName(usernameList);
            }
            System.out.println("getFamilyName: " + familyVo.getFamilyName());
        }

        System.out.println("最终的familyVo: " + familyVo);
        return familyVo;
    }
}
